<template>
    <div class="container" id="main"> 

    </div>
</template>

<script setup lang="ts"> 
import * as echarts from 'echarts';
import { onMounted, onUnmounted, ref, watch } from 'vue';
import { fishWeightApi } from "@/api/fishWeight";

// 添加图表实例引用
let myChart: echarts.ECharts | null = null;

onMounted(function(){
// 保存DOM引用并添加容器尺寸检查
var chartDom = document.getElementById('main');
if (chartDom) {
    // 确保容器有尺寸
    chartDom.style.width = '100%';
    chartDom.style.height = '100%';
    
    myChart = echarts.init(chartDom);
    var option;
    
    fishWeightApi.getLocationStatistics().then(res => {
      // 统计每个称重器ID出现的次数
      const statistics: { [key: string]: number } = {};
      res.data.forEach((item: any) => {
        const scaleId = item.shedNo || '未知';
        statistics[scaleId] = (statistics[scaleId] || 0) + 1;
      });

      // 转换为图表需要的格式，按数量排序并限制最多显示5个
      const sortedData = Object.entries(statistics)
        .sort((a, b) => (b[1] as number) - (a[1] as number)) // 按数量降序排序
        .slice(0, 5); // 只取前5个数据
      
      const xAxisData = sortedData.map(item => item[0]);
      const seriesData = sortedData.map(item => item[1]);

    option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          data: xAxisData,
          axisTick: {
            alignWithLabel: true
          },
          // 添加x轴字体大小设置
          axisLabel: {
            color: 'whitesmoke',
            fontSize: 18
          }
        }
      ],
      yAxis: [
        {
          type: 'value',
          // 添加y轴字体大小设置
          axisLabel: {
            color: 'whitesmoke',
            fontSize: 18
          }
        }
      ],
      series: [
        {
          name: '次数',
          type: 'bar',
          barWidth: '60%',
          data: seriesData
        }
      ]
    };

    option && myChart.setOption(option);
    
    // 添加响应式处理
    const handleResize = () => {
        if (myChart) {
            myChart.resize();
        }
    };
    
    window.addEventListener('resize', handleResize);
    
    onUnmounted(() => {
        window.removeEventListener('resize', handleResize);
    });
    
    setTimeout(() => {
        if (myChart) {
            myChart.resize();
        }
    }, 0);
   });
}
});

// 添加组件卸载时的清理工作
onUnmounted(() => {
    if (myChart) {
        myChart.dispose();
        myChart = null;
    }
});
</script>

<style scoped>
.container{
    width: 100%;
    height: 100%;
}
</style>